<template>
  <div>
    <div class='city-search'>
      <input class='search-input' v-model="keyword" type="text" placeholder="请输入名称">
    </div>
    <div class="search-content" v-show="keyword">
      <ul>
        <li class='search-item' v-for="(item, index) in list" :key="index" @click="handleCityClick(item.name)">{{item.name}}</li>
        <li class='search-item' v-show="!list.length">没有找到匹配数据</li>
      </ul>
    </div>
  </div>

</template>

<script>
export default {
  props: {
    cities: Object
  },
  data() {
    return {
      keyword: "",
      list: [],
      timer: null
    };
  },
  methods: {
    handleCityClick(city) {
      this.$store.commit("changeCity", city)
      this.$router.push("/home")
    }
  },
  watch: {
    keyword() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      if (!this.keyword) {
        this.list = [];
        return;
      }
      this.timer = setTimeout(() => {
        const result = [];
        for (let i in this.cities) {
          this.cities[i].forEach(item => {
            if (
              item.spell.indexOf(this.keyword) > -1 ||
              item.name.indexOf(this.keyword) > -1
            ) {
              result.push(item);
            }
          });
        }
        this.list = result;
      }, 100);
    }
  }
};
</script>


<style lang='stylus' scoped>
@import '~styles/varibles.styl';

.city-search {
  height: 0.72rem;
  padding: 0.1rem;
  background-color: $bgColor;

  .search-input {
    height: 0.62rem;
    line-height: 0.62rem;
    width: 100%;
    text-align: center;
    border-radius: 0.06rem;
    color: #666;
    padding: 0, 0.1rem;
    box-sizing: border-box;
  }
}

.search-content {
  position: absolute;
  top: 1.68rem;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
  background-color: #fff;

  .search-item {
    line-height: 0.62rem;
    color: #666;
    padding-left: 0.2rem;
    background-color: #FFF;
  }
}
</style>
